<?php


/**
 * 得到操作系统信息
 * @return string
 */
function get_system() {
    $sys = $_SERVER['HTTP_USER_AGENT'];
    if (stripos($sys, "NT 6.1")) {
        $os = "Windows 7";
    } else if (stripos($sys, "NT 6.3")) {
        $os = "Windows 8";
    }  else if (stripos($sys, "NT 5.1")) {
        $os = "Windows Vista";
    }  else if (stripos($sys, "NT 5.1")) {
        $os = "Windows XP";
    } else if (stripos($sys, "NT 5.2")) {
        $os = "Windows Server 2003";
    } else if (stripos($sys, "NT 5")) {
        $os = "Windows 2000";
    } else if (stripos($sys, "NT 4.9")) {
        $os = "Windows ME";
    } else if (stripos($sys, "NT 4")) {
        $os = "Windows NT 4.0";
    } else if (stripos($sys, "98")) {
        $os = "Windows 98";
    } else if (stripos($sys, "95")) {
        $os = "Windows 95";
    } else if (stripos($sys, "Mac")) {
        $os = "Mac";
    } else if (stripos($sys, "Linux")) {
        $os = "Linux";
    } else if (stripos($sys, "Unix")) {
        $os = "Unix";
    } else if (stripos($sys, "FreeBSD")) {
        $os = "FreeBSD";
    } else if (stripos($sys, "SunOS")) {
        $os = "SunOS";
    } else if (stripos($sys, "BeOS")) {
        $os = "BeOS";
    } else if (stripos($sys, "OS/2")) {
        $os = "OS/2";
    } else if (stripos($sys, "PC")) {
        $os = "Macintosh";
    } else if(stripos($sys, "AIX")) {
        $os = "AIX";
    } else {
        $os = "未知操作系统";
    }
    return $os;
}

/**
 * 获取系统ip
 * @return unknown|string
 */
function get_client_ip(){
	static $ip;
	if(isset($ip)){
		return $ip;
	}
	$ip = '';
	if($ip = getenv('HTTP_CLIENT_IP')){
		return $ip;
	}else if($ip = getenv('HTTP_X_FORWARDED_FOR')){
		return $ip;
	}else if($ip = getenv('REMOTE_ADDR')){
		return $ip;
	}else{
		$ip = '127.0.0.1';
		return $ip;
	}
}

/**
 * show message
 * 显示提示信息并跳转
 */
function showmessage($message="",$status=200,$timeout=3,$url=""){
        $CI =& get_instance();
        $CI->load->view($url);
}

/**
 * api响应给客户端
 * @param number $status   	返回状态 200成功 300失败
 * @param string $msg     	操作信息的提示信息
 * @param array $data     	需要返回的信息
 */

function api_response($status = 200,$msg = "",$data = array()){
	$json_data = array(
			'status'=>$status,
			"msg"=>$msg,
			"data"=>$data
	);
	echo json_encode($json_data);
	exit;
}



/**
 *   生成短信验证码
 *    authod wzp
 */
function getRandomString($len=6, $chars=null)
{
	if (is_null($chars)){
		$chars = "0123456789";
	}
	mt_srand(10000000*(double)microtime());
	for ($i = 0, $str = '', $lc = strlen($chars)-1; $i < $len; $i++){
		$str .= $chars[mt_rand(0, $lc)];
	}
	return $str;
}
/**
 *  生成随机字符串
 */
function getrandstring($len=6, $chars=null){
	if (is_null($chars)){
		$chars = "0123456789abcdefghijklmnopqrstuvwxyz";
	}
	mt_srand(10000000*(double)microtime());
	for ($i = 0, $str = '', $lc = strlen($chars)-1; $i < $len; $i++){
		$str .= $chars[mt_rand(0, $lc)];
	}
	return $str;
}


/**
 *  curl请求
 * @param string $url
 * @param array $str
 */
function http_post_curl($url, $str = array()){
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_HTTPHEADER, 'application/x-www-form-urlencoded');
	curl_setopt($ch, CURLOPT_HTTPHEADER, 'HOST: www.baidu.com');
	curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
	curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
	curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $str);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
	$response = curl_exec($ch);
	if(curl_errno($ch)){
		$response['error'] = curl_error($ch);
		curl_close($ch);
		return $response;
	}
	curl_close($ch);
	return $response;
}


function baidu_location_city($location = ""){
	$url = "http://api.map.baidu.com/geocoder/v2/?ak=DLYhPwVeiqBCHMDYowR4enmm&
			callback=renderReverse&location={$location}
			&output=json&pois=0";
	$baidu_location = file_get_contents($url);
	if(!$baidu_location){
		return false;
	}
	$baidu_location_arr = json_decode($baidu_location);
	if(isset($baidu_location_arr->result->addressComponent->city) && $baidu_location_arr->result->addressComponent->city){
		$city_name = $baidu_location_arr->result->addressComponent->city;
		$location_address = $baidu_location_arr->result->formatted_address;
		return array('city_name'=>$city_name,'location_address'=>$location_address);
	}
	return false;
}


/**
 *计算某个经纬度的周围某段距离的正方形的四个点
 *
 *@param lng float 经度
 *@param lat float 纬度
 *@param distance float 该点所在圆的半径，该圆与此正方形内切，默认值为50千米
 *@return array 正方形的四个点的经纬度坐标
 */
function returnSquarePoint($lng, $lat,$distance = 50){
	$earth = 6371;
	$dlng =  2 * asin(sin($distance / (2 * $earth)) / cos(deg2rad($lat)));
	$dlng = rad2deg($dlng);

	$dlat = $distance/$earth;
	$dlat = rad2deg($dlat);

	return array(
			'left-top'=>array('lat'=>$lat + $dlat,'lng'=>$lng-$dlng),
			'right-top'=>array('lat'=>$lat + $dlat, 'lng'=>$lng + $dlng),
			'left-bottom'=>array('lat'=>$lat - $dlat, 'lng'=>$lng - $dlng),
			'right-bottom'=>array('lat'=>$lat - $dlat, 'lng'=>$lng + $dlng)
	);
}

/**
 *求两个已知经纬度之间的距离,单位为米
 *@param lng1,lng2 经度
 *@param lat1,lat2 纬度
 *@return float 距离，单位米
 **/
function getdistance($lng1,$lat1,$lng2,$lat2){
	//将角度转为狐度
	$radLat1=deg2rad($lat1);//deg2rad()函数将角度转换为弧度
	$radLat2=deg2rad($lat2);
	$radLng1=deg2rad($lng1);
	$radLng2=deg2rad($lng2);
	$a=$radLat1-$radLat2;
	$b=$radLng1-$radLng2;
	$s=2*asin(sqrt(pow(sin($a/2),2)+cos($radLat1)*cos($radLat2)*pow(sin($b/2),2)))*6378.137*1000;

	return $s;
}



/**
 * 只保留2位
 * @param float $money
 */
function money_round2($money){
	return sprintf("%.2f", $money);
	//return substr(sprintf("%.4f", $money), 0, -2);
}

function money_round($money){
	return substr(sprintf("%.2f", $money), 0, -3);
}
/**
 * 米转为公里
 * @param unknown $s
 * @return string
 */
function  m_to_km($s){
	if(floor($s/1000) >= 1){
		return money_round2($s/1000).'公里';
	}else{
		return money_round2($s).'米';
	}
}

/**
 * 打印日志信息
 * @param unknown $file
 * @param unknown $content
 */
function api_log_print($content){
	$log_file = date('Y-m-d').'_log.log';
	$log_dir = FCPATH.'/log/';
	rec_mkdir($log_dir);
	$fp = fopen($log_dir.'/'.$log_file, 'a+');
	if($fp){
		fwrite($fp, date('Y-m-d H:i:s',time()).'    '.$content."\n");
		fclose($fp);
	}
	
}

/**
 * 
 * @param unknown $string
 * @param unknown $operation D  E
 * @param string $key
 * 
 */
function zsh_encrypt($string,$operation,$key='taoxin_xffl'){ 
	$key = md5($key); 
	$key_length = strlen($key); 
	$string = $operation=='D' ? base64_decode($string) : substr(md5($string.$key),0,8).$string; 
	$string_length = strlen($string); 
	$rndkey = $box = array(); 
	$result=''; 
	for($i=0;$i<=255;$i++){ 
		$rndkey[$i]=ord($key[$i%$key_length]); 
		$box[$i]=$i; 
	} 
	for($j=$i=0;$i<256;$i++){ 
		$j=($j+$box[$i]+$rndkey[$i])%256; 
		$tmp=$box[$i]; 
		$box[$i]=$box[$j]; 
		$box[$j]=$tmp; 
	} 
	for($a=$j=$i=0;$i<$string_length;$i++){ 
		$a=($a+1)%256; 
		$j=($j+$box[$a])%256; 
		$tmp=$box[$a]; 
		$box[$a]=$box[$j]; 
		$box[$j]=$tmp; 
		$result.=chr(ord($string[$i])^($box[($box[$a]+$box[$j])%256])); 
	} 
	if($operation=='D'){ 
		if(substr($result,0,8)==substr(md5(substr($result,8).$key),0,8)){ 
			return substr($result,8); 
		}else{ 
			return''; 
		} 
	}else{ 
		return str_replace('=','',base64_encode($result)); 
	} 
} 

/**
 * 把html转换成txt
 * @param unknown $html
 */
function html_to_txt($html){
	$search = array ("'<script[^>]*?>.*?</script>'si",  // 去掉 javascript
			"'<[\/\!]*?[^<>]*?>'si",           // 去掉 HTML 标记
			"'([\r\n])[\s]+'",                 // 去掉空白字符
			"'&(quot|#34);'i",                 // 替换 HTML 实体
			"'&(amp|#38);'i",
			"'&(lt|#60);'i",
			"'&(gt|#62);'i",
			"'&(nbsp|#160);'i",
			"'&(iexcl|#161);'i",
			"'&(cent|#162);'i",
			"'&(pound|#163);'i",
			"'&(copy|#169);'i",
			"'&#(\d+);'e");                    // 作为 PHP 代码运行

	$replace = array ("",
			"",
			"\\1",
			"\"",
			"&",
			"<",
			">",
			" ",
			chr(161),
			chr(162),
			chr(163),
			chr(169),
			"chr(\\1)");

			return preg_replace ($search, $replace, $html);
}


/**
 * 截取字符串
 * @param unknown $str
 * @param unknown $len
 * @param string $append
 * @return unknown|string|string|unknown
 */
function string_mb_cut($str , $len , $append = false){
	$i = $l = 0;
	$slen = strlen($str);
	$s = $str;
	if($slen <= $len){
		return $s;
	}
	while($i < $slen){
		if(ord($str{$i}) < 0x80){
			$l++; $i++;
		}else if(ord($str{$i}) < 0xe0){
			$l++; $i+=2;
		}else if(ord($str{$i}) < 0xf0){
			$l+=2; $i+=3;
		}else if(ord($str{$i}) < 0xf8){
			$l+=1; $i+=4;
		}else if(ord($str{$i}) < 0xfc){
			$l+=1; $i+=5;
		}else if(ord($str{$i}) < 0xfe){
			$l+=1; $i+=6;
		}
		if($l >= $len){
			$s = substr($str , 0 , $i);
			if($append && ($i < $slen)){
				$s = $s.'...';
			}
			return $s;
		}
	}
	return $s;
}

function echo_json(array $data) {
	header('Content-Type: application/json; charset=utf-8');
	echo json_encode($data);
}

/**
 * 闪存消息
 * @param string $message
 * @param string $prefix
 * @param string $postfix
 * @return bool
 */
function flash_message( $message = null, $prefix = '', $postfix = '' ) {
	$cookie_name = 'taoxin_log_admin_message';
	if ( !empty($message) ) {	// add
		setcookie($cookie_name, base64_encode($message), time()+3600, '/');
	}
	else {	// get
		if( isset($_COOKIE[$cookie_name]) ) {
			$__message = base64_decode( $_COOKIE[$cookie_name] );
			setcookie($cookie_name,  '', time()-3600, '/');
			if( !empty($prefix) && !empty($postfix) ) {
				echo $prefix . $__message . $postfix;
			}
			else {
				echo "<div class='alert alert-info taoxin_logtip'>
						<i class='icon-hand-right'></i>
						{$__message}
						<button class='close' data-dismiss='alert'>
							<i class='icon-remove'></i>
						</button>
					</div>";
			}
		}
		else {
			return FALSE;
		}
	}
}


/**
 * 设置获取获取COOKIE值
 * @param string $k
 * @param string $v
 * @param string $expire
 * @param string $path
 * @param string $domain
 * @return mixed
 */
function zsh_log_cookie($k, $v = NULL, $expire = 0, $path = '/', $domain = NULL) {
	// 获取
	if ($k && is_null($v)) {
		if (isset($_COOKIE[$k])) {
			return urldecode($_COOKIE[$k]);
		}
	}
	// 设置
	else {
		setcookie($k, urlencode($v), $expire, $path, $domain);
	}
}

/**
 * 
 *加密与解密函数  COPY TO qibocms
 * @param unknown $string  加密字符串
 * @param string $action   EN加密 DE解密
 * @param string $rand     加密数字
 */
function zsh_encryption($string,$action="EN",$rand='taoxin_logistics'){ //字符串加密和解密
	if($action=="DE"){//处理+号在URL传递过程中会异常
		$string = str_replace('TAOXIN|ADD','+',$string);
		$string = str_replace('TAOXIN|EQTO','=',$string);
		$string = str_replace('TAOXIN|ASK','?',$string);
	}
	$secret_string = $rand.'taoxin_logistics_encryption_3446t&^%$@)(+_'; //绝密字符串,可以任意设定
	if(!is_string($string)){
		$string=strval($string);
	}
	if($string==="") {
		return "";
	}
	if($action=="EN"){
		$md5code = substr(md5($string),8,10);
	}else{
		$md5code = substr($string,-10);
		$string = substr($string,0,strlen($string)-10);
	}
	$key = md5($md5code.$secret_string);
	$string = ($action=="EN" ? $string : base64_decode($string));
	$len = strlen($key);
	$code = "";
	for($i=0; $i<strlen($string); $i++){
		$k = $i%$len;
		$code .= $string[$i]^$key[$k];
	}
	$code = ($action == "DE" ? (substr(md5($code),8,10) == $md5code ? $code : NULL) : base64_encode($code)."{$md5code}");
	if($action=="EN"){//处理特殊符号在URL传递过程中会异常
		$code = str_replace('+','TAOXIN|ADD',$code);
		$code = str_replace('=','TAOXIN|EQTO',$code);
		$code = str_replace('?','TAOXIN|ASK',$code);
	}
	return $code;
}

/**
 * 加密内容
 * @param unknown $str
 */
function zsh_encryption_en($str){
	return taoxin_logistics_encryption($str,'EN');
}

/**
 * 解密加密内容
 * @param unknown $str
 */
function zsh_encryption_de($str){
	return taoxin_logistics_encryption($str,'DE');
}

/**
 * 发送邮件
 * @param unknown $title      邮件标题
 * @param unknown $messages   邮件内容
 * @param string $to		   发送给那个
 */
function  send_mail($title,$messages,$to = "670513345@qq.com"){
	require_once APPPATH.'third_party/mail/class.phpmailer.php';
	require_once APPPATH.'third_party/mail/class.smtp.php';
	$sms_mail_user =  "system@taihewuliu.com";
	$sms_mail_pwd =  "850c040b3C";
	$sms_mail_host = "smtp.exmail.qq.com";
	$mail = new phpmailer();
	$mail->IsSMTP();
	$mail -> CharSet = 'utf-8';
	$mail -> Body = $messages;
	$mail->From = $sms_mail_user;
	$mail->FromName = "泰合客户服务平台";
	$mail->Subject = $title;
	//添加密送
	//$mail->addBCC('mail4@qq.com'); 
	// 设置SMTP服务器。这里使用网易的SMTP服务器。
	$mail->Host = $sms_mail_host;
	$mail->IsHTML(true);
	$mail->SMTPAuth = true;
	// 设置用户名和密码，即网易邮件的用户名和密码。
	$mail->Username    = $sms_mail_user;
	$mail-> Password  = $sms_mail_pwd;
	$mail-> AddAddress( $to );
	
	if ( !$mail -> Send() ){
		return false;
	}else{
		return true;
	}
}




/**
 * 传入一个字符串  自动截取后六位  只保留数字部分  如568975000002  只会返回2
 * @param string $str_number
 */
function mb_str_out_left_six($str_number = ""){
	$number = substr($str_number,-6);
	return preg_replace('/^0+/','',$number);
}

/**
 * 传入一个字符串  自动截取后六位  只保留数字部分  如568975000002  只会返回568975
 * @param string $str_number
 */
function mb_str_out_right_six($str_number = ""){
	$number = substr($str_number,0,6);
	return $number;
}

/**
 * 数字自动补零   如
 * 2 变为 000002
 * @param unknown $number
 */
function str_to_left_zreo($number){
	return str_pad($number, 6, "0", STR_PAD_LEFT);
}

/**
 * 物品取整
 * @param unknown $float
 */
function weight_ceil($float){
	return ceil($float);
}




function  zsh_validate($value,$key){
	switch ($key) {
		case "number"://正整数验证
			return preg_match("/^(0|[1-9]\d*)$/", $value);
			break;

		case 'number_float_3'://验证正的三位小数
			return preg_match(" /^(0|[1-9]\d*)(\.\d{0,3})?$/", $value);
			break;
		case 'number_float_2':
			return preg_match(" /^(0|[1-9]\d*)(\.\d{0,2})?$/", $value);
			break;
		case 'negative_number_float_2':
			return preg_match(" /^-?(0|[1-9]\d*)(\.\d{0,2})?$/", $value);
			break;
	}

}


function account_money_format($number){
	return  number_format($number,2,'.',',');
}
/**
 * 正则替换内容的img地址
 *
 */
function help_content_full_img_url($matches){
	if(isset($matches[2]) && $matches[2]){
		$url = $matches[2];
		//判断地址是否完整
		if(!preg_match('/(http|https):\/\/[\w.]+[\w\/]*[\w.]*\??[\w=&\+\%]*/is',$url)){
			return "<img src='http://www.86zsh.com".$url."'  />";
		}else{
			return "<img src='{$url}'  />";
		}
	}else{
		return "";
	}
}

function help_zsh_content_full_img($content){
	return preg_replace_callback('/<img(.*)?src="([^"]+)"[^>]+>/isU',"help_content_full_img_url" , $content);
}

/**
 * 给img赋完整地址
 */ 
function help_full_img_url($content){
	if(!preg_match('/(http|https):\/\/[\w.]+[\w\/]*[\w.]*\??[\w=&\+\%]*/is',$content)){
		$content = ltrim($content,'/');
		return "http://www.86zsh.com/".$content;
	}else{
		return $content;
	}
}

function member_incutry_name_nav($name){
	$len = mb_strlen($name,'utf8');
	if($len == 2){
		$left = mb_substr($name,0,1,"UTF-8");//hp点
		$right = mb_substr($name,-1,1,"UTF-8");//hp点
		return $left."&nbsp;&nbsp;".$right;
	}else{
		return $name;
	}
}

function apiResponse($status = 200,$msg = "",$data = array()){
	$json_data = array(
			'status'=>$status,
			"msg"=>$msg,
			"data"=>$data
	);
	echo json_encode($json_data);
	exit;
}

?>